//
//  ShangHuHaoDetailViewController.m
//  ShouKuang
//
//  Created by CodeYY on 2019/5/31.
//  Copyright © 2019 CodeYY. All rights reserved.
//

#import "ShangHuHaoDetailViewController.h"
#import "GeRenXinXiViewController.h"

#import "AddGuanLiYuanViewController.h"
#import "AlertOperationView.h"
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)


@interface ShangHuHaoDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableDictionary *dic;
@property (strong, nonatomic) NSIndexPath* editingIndexPath;  //当前左滑cell的index，在代理方法中设置

@end

@implementation ShangHuHaoDetailViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *cachePolicyPath = [[NSBundle mainBundle] pathForResource:@"shanghuhaoDetial" ofType:@"json"];
    _dic= [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:[[NSData alloc] initWithContentsOfFile:cachePolicyPath] options:kNilOptions error:nil]] ;

    [self initNavBar];
    [self initCustomUI];
    // Do any additional setup after loading the view.
}

-(void)initNavBar
{
    WEAKSELF
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:[UIImage imageNamed:@"nav_back_red"] forState:UIControlStateNormal];
    [leftBtn setTitle:@"返回" forState:UIControlStateNormal];
    [leftBtn setTitleColor:YYRGB(129, 129, 129) forState:UIControlStateNormal];
    [leftBtn jk_setImagePosition:LXMImagePositionLeft spacing:5];
    [[leftBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
    self.title = @"商户号详情";
    
}
- (void)initCustomUI
{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 70, Main_Screen_Width, Main_Screen_Height - 70) style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    _tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCells"];
    
}

- (void)viewDidLayoutSubviews{
    
    [super viewDidLayoutSubviews];
    
    [self configSwipeButtons];
    
}

#pragma mark -delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
     return   [[_dic valueForKey:@"商户号详情key"] allKeys].count;
    }else if (section == 1){
        return [[_dic valueForKey:@"管理员key"] count];
    }else if (section == 2){
        return [[_dic valueForKey:@"收银员key"] count];
    }
    return 0;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 || indexPath.section == 2) {
        return YES;
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.editingIndexPath = indexPath;
    [self.view setNeedsLayout];   // 触发-(void)viewDidLayoutSubviews
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.editingIndexPath = nil;
}
- (void)configSwipeButtons
{
    // 获取选项按钮的reference
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"11.0"))
    {
        // iOS 11层级 (Xcode 9编译): UITableView -> UISwipeActionPullView
        for (UIView *subview in self.tableView.subviews)
        {
            if ([subview isKindOfClass:NSClassFromString(@"UISwipeActionPullView")])
            {
                // 和iOS 10的按钮顺序相反
                UIButton *deleteButton = subview.subviews[0];
                [self configDeleteButton:deleteButton];
            }
        }
    }
    else
    {
        // iOS 8-10层级: UITableView -> UITableViewCell -> UITableViewCellDeleteConfirmationView
        UITableViewCell *tableCell = [self.tableView cellForRowAtIndexPath:self.editingIndexPath];
        for (UIView *subview in tableCell.subviews)
        {
            if ([subview isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")])
            {
                UIButton *deleteButton = subview.subviews[0];
//                UIButton *readButton = subview.subviews[1];
                
                [self configDeleteButton:deleteButton];
//                [subview setBackgroundColor:[[ColorUtil instance] colorWithHexString:@"E5E8E8"]];
            }
        }
    }
    
}

- (void)centerImageAndTextOnButton:(UIButton*)button
{
    // this is to center the image and text on button.
    // the space between the image and text
    CGFloat spacing = 15.0;
    
    // lower the text and push it left so it appears centered below the image
    CGSize imageSize = button.imageView.image.size;
    button.titleEdgeInsets = UIEdgeInsetsMake(0.0, imageSize.width / 2, - (imageSize.height + spacing), 0.0);
    
    // raise the image and push it right so it appears centered above the text
    CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: button.titleLabel.font}];
    button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
    
    // increase the content height to avoid clipping
    CGFloat edgeOffset = (titleSize.height - imageSize.height) / 2.0;
    button.contentEdgeInsets = UIEdgeInsetsMake(edgeOffset, 0.0, edgeOffset, 0.0);
    
    // move whole button down, apple placed the button too high in iOS 10
    if (SYSTEM_VERSION_LESS_THAN(@"11.0"))
    {
        CGRect btnFrame = button.frame;
        btnFrame.origin.y = 18;
        button.frame = btnFrame;
    }
}
- (void)configDeleteButton:(UIButton*)deleteButton
{
    if (deleteButton)
    {
        [deleteButton setTitle:@"删除" forState:UIControlStateNormal];
//        [deleteButton.titleLabel setFont:[UIFont fontWithName:@"SFUIText-Regular" size:12.0]];
//        [deleteButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [deleteButton setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
//        [deleteButton jk_setImagePosition:(LXMImagePositionTop) spacing:0];
//        [deleteButton setBackgroundColor:[UIColor redColor];
        // 调整按钮上图片和文字的相对位置（该方法的实现在下面）
        [self centerImageAndTextOnButton:deleteButton];
    }
}


- (NSArray*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    // delete action
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
                                          {
                                              [AlertOperationView alertOperationView:nil titleStr:(indexPath.section == 1 ? @"是否删除该商品管理员" : @"是否删除该收银员") sureBtnBlock:^{
                                                  
                                                  [tableView setEditing:NO animated:YES];  // 这句很重要，退出编辑模式，隐藏左滑菜单
                                                  if (indexPath.section == 1) {
                                                      NSMutableArray *mutaAry =[NSMutableArray arrayWithArray:[weakSelf.dic valueForKey:@"管理员key"]];
                                                      [mutaAry removeObjectAtIndex:indexPath.row];
                                                      weakSelf.dic[@"管理员key"] = mutaAry;
                                                  }else{
                                                      NSMutableArray *mutaAry =[NSMutableArray arrayWithArray:[weakSelf.dic valueForKey:@"收银员key"]];
                                                      [mutaAry removeObjectAtIndex:indexPath.row];
                                                      weakSelf.dic[@"收银员key"] = mutaAry;
                                                  }
                                                  [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                                                  
                                                  [AlertOperationView alertOperationView:@"success_red" titleStr:@"删除成功" sureBtnBlock:nil cancleBtnBlock:nil];
                                                  
                                              } cancleBtnBlock:^{

                                              }];

                                              
                                              
                                              
                                        
                                          }];
    
    return @[deleteAction];
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCells" forIndexPath:indexPath];
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    
    if (indexPath.section == 0) {
        UILabel *titleLab = [UILabel new];
        [cell addSubview:titleLab];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(16);
            make.top.offset(12);
        }];
        titleLab.textColor = [UIColor lightGrayColor];
        
        UILabel *contentLab = [UILabel new];
        [cell addSubview:contentLab];
        [contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(16);
            make.top.equalTo(titleLab.mas_bottom).offset(12);
        }];
        contentLab.textColor = [UIColor darkGrayColor];
        // 赋值
        titleLab.text = [[_dic valueForKey:@"商户号详情key"]allKeys][indexPath.row];
        contentLab.text = [[_dic valueForKey:@"商户号详情key"] valueForKey:[[_dic valueForKey:@"商户号详情key"]allKeys][indexPath.row]];
        
    }else if (indexPath.section == 1 || indexPath.section == 2){
        UIImageView *img = [UIImageView new];
        [cell addSubview:img];
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(16);
            make.centerY.offset(0);
            make.size.mas_equalTo(CGSizeMake(35, 35));
        }];
        img.layer.cornerRadius = 35/2;
        img.layer.masksToBounds = YES;
        
        UILabel *titleLab = [UILabel new];
        [cell addSubview:titleLab];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(img.mas_right).offset(10);
            make.centerY.offset(0);
        }];
        titleLab.textColor = [UIColor lightGrayColor];
        
        UILabel *contentLab = [UILabel new];
        [cell addSubview:contentLab];
        [contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-16);
            make.centerY.offset(0);
        }];
        contentLab.textColor = [UIColor darkGrayColor];
        
        // 赋值
        img.backgroundColor = [UIColor greenColor];
        
        NSDictionary *contentDic;
        if (indexPath.section == 1) {
            contentDic = [_dic valueForKey:@"管理员key"][indexPath.row];
        }else{
            contentDic = [_dic valueForKey:@"收银员key"][indexPath.row];
        }
        titleLab.text = [contentDic valueForKey:@"name"];
        contentLab.text = [contentDic valueForKey:@"type"];
    }
    
    UIView *line  = [UIView new];
    [cell addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.mas_equalTo(1);
    }];
    line.backgroundColor = [UIColor darkGrayColor];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        GeRenXinXiViewController *vc = [GeRenXinXiViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 70;
    }else{
        return 60;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    __weak typeof(self) weakSelf = self;
    if (section == 0) {
        return nil;
    }else{
        UIView *view = [UIView new];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
            if (section == 0) {
                AddGuanLiYuanViewController *vc = [AddGuanLiYuanViewController addGuanLiYuanViewController:ShouYiAddType];
                [weakSelf.navigationController pushViewController:vc animated:YES];

            }else{
                AddGuanLiYuanViewController *vc = [AddGuanLiYuanViewController addGuanLiYuanViewController:GuanLiAddType];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }
        }];
        [view addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.height.mas_equalTo(50);
            make.centerY.offset(0);
        }];
        if (section == 1) {
            [btn setTitle:@"添加商户号管理员" forState:UIControlStateNormal];
        }else{
            [btn setTitle:@"添加收银员" forState:UIControlStateNormal];
        }
        return view;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 20;
    }else{
        return 120;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   if (section == 1 && [[_dic valueForKey:@"管理员key"] count]){
        return 50;
   }else if (section == 2 && [[_dic valueForKey:@"收银员key"] count]){
       return 50;
   }
  return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }else{
        UIView *view = [UIView new];
        view.backgroundColor = [UIColor whiteColor];
        UILabel *headLab = [UILabel new];
        [view addSubview:headLab];
        [headLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.left.offset(16);
        }];
        if (section == 1) {
            headLab.text = @"商户号管理员";
        }else{
            headLab.text = @"收银员";
        }
        return view;
    }

}
@end
